//
//  JXOauthController.swift
//  01-weiboSwift
//
//  Created by TwistFate on 16/2/27.
//  Copyright © 2016年 TwistFate. All rights reserved.
//

import UIKit
import SVProgressHUD

class JXOauthController: UIViewController {

    lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = JXNetworkTool.sharedInstance.oauthLoginUrl()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)

        setupNavgationBar()
    }

    func setupNavgationBar () {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func autoFill() {
        let js = "document.getElementById('userId').value='718189587@qq.com';document.getElementById('passwd').value='z8891988'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
   
    func close() {
        SVProgressHUD.dismiss()
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
}

extension JXOauthController : UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("loading", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
        print("error:\(error)")
        if error?.code != 102{
            SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
        }
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        
        if urlString!.hasPrefix(JXNetworkTool.sharedInstance.redirect_uri){
            
            let query = request.URL?.query
            let codeStr = "code="
            if query!.hasPrefix(codeStr){
                let queryNS = query! as NSString
//                query?.substringFromIndex(<#T##index: Index##Index#>)
                let code = queryNS.substringFromIndex(codeStr.characters.count)
                
                JXUserAcountViewModel.sharedInstance.loadUserAcount(code, loadAccessTokenCallBack: { (error) -> () in
                    if error != nil{
                        SVProgressHUD.showErrorWithStatus("请检查你的网络")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            // 关闭控制器
                            self.close()
                        })
                    }
                    return
                })
                
                //账号保存成功了
                close()
                let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
                appDelegate?.switchRootController(false)
//                SVProgressHUD.dismiss()
            }else{
                close()
                
            }
            
            return false
        }else{
            return true
        }
    }
}

